package com.pkutech.carcasher.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.pkutech.carcasher.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WebContentActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {

    public static final String TAG_TITLE = "TAG_TITLE";
    public static final String TAG_URL = "TAG_URL";
    public static final String TAG_FIRM_ID = "TAG_FIRM_ID";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.webView1)
    WebView web;
    @BindView(R.id.loadProgress)
    ProgressBar loadProgress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_content);
        ButterKnife.bind(this);
        initToolbar(toolbar);

        String url = this.getIntent().getStringExtra(TAG_URL);
        String title = this.getIntent().getStringExtra(TAG_TITLE);
        String firmID = getIntent().getStringExtra(TAG_FIRM_ID);
        setTitle(title);

        web = (WebView) this.findViewById(R.id.webView1);
        web.setWebViewClient(new SampleWebViewClient());

        web.addJavascriptInterface(new JSInvokeClass(), "androidApi");

        WebSettings webSettings = web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        webSettings.setGeolocationEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        web.setWebChromeClient(new GeoClient());
        web.clearCache(true);

//        if (TextUtils.isEmpty(firmID))
//            web.loadUrl(TextUtils.isEmpty(url) ? "http://www.rokyinfo.net/footer/productdesc.htm" : url);
//        else
//            vendorInfo(firmID);

        web.loadUrl(TextUtils.isEmpty(url) ? "http://www.rokyinfo.net/footer/productdesc.htm" : url);

        web.setDownloadListener(new MyWebViewDownLoadListener());
        loadProgress = (ProgressBar) findViewById(R.id.loadProgress);

    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.web_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_refresh) {
            loadProgress.setVisibility(View.VISIBLE);
            web.clearCache(true);
            web.reload();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (web.canGoBack()) {
            web.goBack();
        } else {
            finish();
        }
    }

    @Override
    public void onDestroy() {
        if (null != web) {
            ((RelativeLayout) findViewById(R.id.webLayout)).removeView(web);
            web.destroy();
        }
        super.onDestroy();

    }

    @Override
    public void onRefresh() {
        web.reload();
    }

    private class SampleWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Return false so the WebView loads the url
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

//            loadProgress.setVisibility(View.GONE);
        }
    }

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }

    class GeoClient extends WebChromeClient {

        //配置权限（同样在WebChromeClient中实现）
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        public void onProgressChanged(WebView view, int newProgress) {
            Log.d("cyy", "newProgress: " + newProgress);

            if (newProgress == 100) {

                loadProgress.setVisibility(View.GONE);
                loadProgress.setProgress(0);

            } else {

                if (loadProgress.getVisibility() == View.GONE) {
                    loadProgress.setVisibility(View.VISIBLE);
                }
                loadProgress.setProgress(newProgress);

            }

        }

    }

    class JSInvokeClass {

        @JavascriptInterface
        public void login() {
            WebContentActivity.this.finish();
        }

    }

}
